package com.ruoyi.reportInfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.reportInfo.domain.IndustrialLogisticsCompanyOperation;
import com.ruoyi.reportInfo.mapper.IndustrialLogisticsCompanyOperationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.reportInfo.domain.bo.IndustrialLogisticsCompanyBo;
import com.ruoyi.reportInfo.domain.vo.IndustrialLogisticsCompanyVo;
import com.ruoyi.reportInfo.domain.IndustrialLogisticsCompany;
import com.ruoyi.reportInfo.mapper.IndustrialLogisticsCompanyMapper;
import com.ruoyi.reportInfo.service.IIndustrialLogisticsCompanyService;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 物流企业信息Service业务层处理
 *
 * @author yangzhen
 * @date 2025-11-24
 */
@RequiredArgsConstructor
@Service
public class IndustrialLogisticsCompanyServiceImpl implements IIndustrialLogisticsCompanyService {

    private final IndustrialLogisticsCompanyMapper baseMapper;
    private final IndustrialLogisticsCompanyOperationMapper industrialLogisticsCompanyOperationMapper;

    /**
     * 查询物流企业信息
     */
    @Override
    public IndustrialLogisticsCompanyVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询物流企业信息列表
     */
    @Override
    public TableDataInfo<IndustrialLogisticsCompanyVo> queryPageList(IndustrialLogisticsCompanyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<IndustrialLogisticsCompany> lqw = buildQueryWrapper(bo);
        Page<IndustrialLogisticsCompanyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<IndustrialLogisticsCompanyVo> industrialCompanyPageList(IndustrialLogisticsCompanyBo bo, PageQuery pageQuery) {

        LambdaQueryWrapper<IndustrialLogisticsCompany> lqw = buildQueryWrapper(bo);

        // 1. 分页查公司数据
        Page<IndustrialLogisticsCompanyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<IndustrialLogisticsCompanyVo> records = result.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return TableDataInfo.build(result);
        }

        // 2. 获取今年的年度
        int currentYear = LocalDate.now().getYear();

        // 3. 获取所有公司 ID (String)
        List<String> companyIds = records.stream()
            .map(IndustrialLogisticsCompanyVo::getId)
            .collect(Collectors.toList());

        // 4. 一次性查询所有公司今年的运营信息
        List<IndustrialLogisticsCompanyOperation> opList =
            industrialLogisticsCompanyOperationMapper.selectList(
                Wrappers.<IndustrialLogisticsCompanyOperation>lambdaQuery()
                    .in(IndustrialLogisticsCompanyOperation::getCompanyId, companyIds)
                    // 按 report_collect_date 的年份过滤
                    .apply("YEAR(report_collect_date) = {0}", currentYear)
            );

        // 5. 将运营信息按 companyId 分组
        Map<String, List<IndustrialLogisticsCompanyOperation>> opMap = opList.stream()
            .collect(Collectors.groupingBy(IndustrialLogisticsCompanyOperation::getCompanyId));

        // 6. 写入 VO 的年度货运量
        for (IndustrialLogisticsCompanyVo vo : records) {

            List<IndustrialLogisticsCompanyOperation> list = opMap.get(vo.getId());

            if (CollectionUtils.isEmpty(list)) {
                vo.setAnnualCargoVolume(BigDecimal.ZERO);
                continue;
            }

            BigDecimal total = list.stream()
                .map(IndustrialLogisticsCompanyOperation::getOperationWeight)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

            vo.setAnnualCargoVolume(total);
        }

        return TableDataInfo.build(result);
    }


    /**
     * 查询物流企业信息列表
     */
    @Override
    public List<IndustrialLogisticsCompanyVo> queryList(IndustrialLogisticsCompanyBo bo) {
        LambdaQueryWrapper<IndustrialLogisticsCompany> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IndustrialLogisticsCompany> buildQueryWrapper(IndustrialLogisticsCompanyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IndustrialLogisticsCompany> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), IndustrialLogisticsCompany::getCompanyName, bo.getCompanyName());
        lqw.eq(StringUtils.isNotBlank(bo.getUnifiedSocialCode()), IndustrialLogisticsCompany::getUnifiedSocialCode, bo.getUnifiedSocialCode());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyLegaler()), IndustrialLogisticsCompany::getCompanyLegaler, bo.getCompanyLegaler());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyType()), IndustrialLogisticsCompany::getCompanyType, bo.getCompanyType());
        lqw.eq(StringUtils.isNotBlank(bo.getCoreBusiness()), IndustrialLogisticsCompany::getCoreBusiness, bo.getCoreBusiness());
        lqw.eq(bo.getRegisterDate() != null, IndustrialLogisticsCompany::getRegisterDate, bo.getRegisterDate());
        lqw.eq(bo.getRegisterAddress() != null, IndustrialLogisticsCompany::getRegisterAddress, bo.getRegisterAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), IndustrialLogisticsCompany::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getLongitude()), IndustrialLogisticsCompany::getLongitude, bo.getLongitude());
        lqw.eq(StringUtils.isNotBlank(bo.getLatitude()), IndustrialLogisticsCompany::getLatitude, bo.getLatitude());
        lqw.eq(StringUtils.isNotBlank(bo.getBelongParkId()), IndustrialLogisticsCompany::getBelongParkId, bo.getBelongParkId());
        lqw.like(StringUtils.isNotBlank(bo.getBelongParkName()), IndustrialLogisticsCompany::getBelongParkName, bo.getBelongParkName());
        lqw.eq(bo.getCompanyEmployees() != null, IndustrialLogisticsCompany::getCompanyEmployees, bo.getCompanyEmployees());
        lqw.eq(StringUtils.isNotBlank(bo.getManager()), IndustrialLogisticsCompany::getManager, bo.getManager());
        lqw.eq(StringUtils.isNotBlank(bo.getManagerContact()), IndustrialLogisticsCompany::getManagerContact, bo.getManagerContact());
        lqw.eq(bo.getLargeScale() != null, IndustrialLogisticsCompany::getLargeScale, bo.getLargeScale());
        lqw.eq(StringUtils.isNotBlank(bo.getFileList1()), IndustrialLogisticsCompany::getFileList1, bo.getFileList1());
        lqw.eq(StringUtils.isNotBlank(bo.getFileList2()), IndustrialLogisticsCompany::getFileList2, bo.getFileList2());
        lqw.eq(bo.getDataStatus() != null, IndustrialLogisticsCompany::getDataStatus, bo.getDataStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDataSources()), IndustrialLogisticsCompany::getDataSources, bo.getDataSources());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyLevel()), IndustrialLogisticsCompany::getCompanyLevel, bo.getCompanyLevel());
        lqw.eq(bo.getCollectDate() != null, IndustrialLogisticsCompany::getCollectDate, bo.getCollectDate());
        return lqw;
    }

    /**
     * 新增物流企业信息
     */
    @Override
    public Boolean insertByBo(IndustrialLogisticsCompanyBo bo) {
        IndustrialLogisticsCompany add = BeanUtil.toBean(bo, IndustrialLogisticsCompany.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改物流企业信息
     */
    @Override
    public Boolean updateByBo(IndustrialLogisticsCompanyBo bo) {
        IndustrialLogisticsCompany update = BeanUtil.toBean(bo, IndustrialLogisticsCompany.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IndustrialLogisticsCompany entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除物流企业信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
